import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Service } from 'src/module/admin/service/entities/service.entity';
import { ServicePhoto } from 'src/module/admin/service_photo/entities/service_photo.entity';
import { User } from 'src/module/admin/user/entities/user.entity';
import { UserShopId } from 'src/module/admin/user_shop-id/entities/user_shop-id.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ServiceService {
  constructor(
    @InjectRepository(Service)
    private readonly serviceRepository: Repository<Service>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(UserShopId)
    private readonly userShopRepository: Repository<UserShopId>,
    @InjectRepository(ServicePhoto)
    private readonly servicePhotoRepository: Repository<ServicePhoto>,
  ) {}

  // create(createServiceDto: CreateServiceDto) {
  //   return 'This action adds a new service';
  // }

  findAll() {
    return `This action returns all service`;
  }
  async skipFind(
    currentPage: number,
    pageSize: number,
    city: string = '成都',
    keywords?: string,
  ): Promise<Array<Service> | any> {
    let list = null;
    if (keywords) {
      list = await this.serviceRepository
        .createQueryBuilder('service')
        .leftJoinAndSelect('service.shop', 'shop')
        .leftJoinAndSelect('service.photos', 'photos')
        .where('shop.city = :city', { city: city })
        .andWhere('service.isDelete = :isDelete', { isDelete: false })
        .andWhere('service.service_point LIKE :service_point', {
          service_point: `%${keywords}%`,
        })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    } else {
      list = await this.serviceRepository
        .createQueryBuilder('service')
        .leftJoinAndSelect('service.shop', 'shop')
        .leftJoinAndSelect('service.photos', 'photos')
        .where('shop.city = :city', { city: city })
        .andWhere('service.isDelete = :isDelete', { isDelete: false })
        .skip((currentPage - 1) * pageSize)
        .take(pageSize)
        .getManyAndCount();
    }
    return {
      list: list[0],
      total: list[1],
      pageSize,
      currentPage,
      pages: Math.ceil(list[1] / pageSize),
    };
  }

  // 查询单个
  async findOne(id: number): Promise<Service | any> {
    const res = await this.serviceRepository.find({
      where: { id },
      join: {
        alias: 'service',
        leftJoinAndSelect: {
          photo: 'service.photos',
          user: 'service.shop',
        },
      },
    });

    const shopNameId = res[0].shopNameId || '';

    // 根据店铺ID查询出店铺的名称
    const shop = await this.userShopRepository
      .createQueryBuilder('userShopId')
      .where('userShopId.shopId = :shopId ', { shopId: shopNameId })
      .getMany();
    return { ...(res[0] || {}), shopName: shop[0]?.shopName || '' };
  }

  async addService(userId, params) {
    try {
      const user = await this.userRepository.findOne({ where: { id: userId } });
      const service = new Service();
      service.money = params.money;
      service.province = params.province;
      service.city = params.city;
      service.description = params.description;
      service.service_point = params.service_point;
      service.category = params.category;
      service.shopNameId = params.shopNameId;
      service.shop = user;

      const res = await this.serviceRepository.save(service);

      params.serviceImgs.forEach(async (item) => {
        const service = await this.serviceRepository.findOne({
          where: { id: res.id },
        });
        const servicePhoto = new ServicePhoto();
        servicePhoto.url = item.url;
        // 获取到创建好的图片ID
        const { id } = await this.servicePhotoRepository.save(servicePhoto);

        const servicePhotoTemp = await this.servicePhotoRepository.findOne({
          where: { id },
        });
        servicePhotoTemp.service = service;
        await this.servicePhotoRepository.save(servicePhotoTemp);
      });
    } catch (err) {
      return {
        code: 901,
        msg: '新增失败',
      };
    }
    return {
      code: 900,
      msg: '新增成功',
    };
  }

  // update(id: number, updateServiceDto: UpdateServiceDto) {
  //   return `This action updates a #${id} service`;
  // }

  remove(id: number) {
    return `This action removes a #${id} service`;
  }
}
